// 全局状态
let users = []
let tasks = []
let currentUser = null

// DOM 元素
const usersList = document.getElementById('usersList')
const tasksList = document.getElementById('tasksList')
const userFilter = document.getElementById('userFilter')
const taskUser = document.getElementById('taskUser')

// 模态框元素
const userModal = document.getElementById('userModal')
const taskModal = document.getElementById('taskModal')
const userForm = document.getElementById('userForm')
const taskForm = document.getElementById('taskForm')

// 按钮元素
const addUserBtn = document.getElementById('addUserBtn')
const addTaskBtn = document.getElementById('addTaskBtn')
const closeUserModal = document.getElementById('closeUserModal')
const closeTaskModal = document.getElementById('closeTaskModal')
const cancelUserBtn = document.getElementById('cancelUserBtn')
const cancelTaskBtn = document.getElementById('cancelTaskBtn')
const checkUpdateBtn = document.getElementById('checkUpdateBtn')
const updateStatus = document.getElementById('updateStatus')
const updateStatusText = document.getElementById('updateStatusText')

// 初始化应用
async function initApp() {
  try {
    await loadUsers()
    await loadTasks()
    setupEventListeners()
    setupUpdateUI()
    console.log('应用初始化成功')
  } catch (error) {
    console.error('应用初始化失败:', error)
    showError('应用初始化失败: ' + error.message)
  }
}

// 设置事件监听
function setupEventListeners() {
  // 用户相关事件
  addUserBtn.addEventListener('click', showUserModal)
  closeUserModal.addEventListener('click', hideUserModal)
  cancelUserBtn.addEventListener('click', hideUserModal)
  userForm.addEventListener('submit', handleUserSubmit)

  // 任务相关事件
  addTaskBtn.addEventListener('click', showTaskModal)
  closeTaskModal.addEventListener('click', hideTaskModal)
  cancelTaskBtn.addEventListener('click', hideTaskModal)
  taskForm.addEventListener('submit', handleTaskSubmit)

  // 过滤器事件
  userFilter.addEventListener('change', handleUserFilterChange)

  // 更新相关事件
  checkUpdateBtn.addEventListener('click', handleCheckUpdate)

  // 模态框外部点击关闭
  userModal.addEventListener('click', (e) => {
    if (e.target === userModal) hideUserModal()
  })
  taskModal.addEventListener('click', (e) => {
    if (e.target === taskModal) hideTaskModal()
  })
}

// 加载用户数据
async function loadUsers() {
  try {
    const result = await window.api.getUsers()
    if (result.success) {
      users = result.data
      renderUsers()
      updateUserSelects()
    } else {
      throw new Error(result.error)
    }
  } catch (error) {
    console.error('加载用户失败:', error)
    showError('加载用户失败: ' + error.message)
  }
}

// 加载任务数据
async function loadTasks(userId = null) {
  try {
    const result = await window.api.getTasks(userId)
    if (result.success) {
      tasks = result.data
      renderTasks()
    } else {
      throw new Error(result.error)
    }
  } catch (error) {
    console.error('加载任务失败:', error)
    showError('加载任务失败: ' + error.message)
  }
}

// 渲染用户列表
function renderUsers() {
  if (users.length === 0) {
    usersList.innerHTML = `
      <div class="empty-state">
        <h3>暂无用户</h3>
        <p>点击"添加用户"创建第一个用户</p>
      </div>
    `
    return
  }

  usersList.innerHTML = users.map(user => `
    <div class="user-item">
      <div class="user-info">
        <h4>${user.first_name || ''} ${user.last_name || ''} (@${user.username})</h4>
        <p>${user.email}</p>
      </div>
      <div class="user-status ${user.is_active ? 'active' : 'inactive'}">
        ${user.is_active ? '活跃' : '非活跃'}
      </div>
    </div>
  `).join('')
}

// 渲染任务列表
function renderTasks() {
  if (tasks.length === 0) {
    tasksList.innerHTML = `
      <div class="empty-state">
        <h3>暂无任务</h3>
        <p>点击"添加任务"创建第一个任务</p>
      </div>
    `
    return
  }

  tasksList.innerHTML = tasks.map(task => {
    const dueDate = task.due_date ? new Date(task.due_date).toLocaleString('zh-CN') : '无截止日期'
    const createdDate = new Date(task.created_at).toLocaleString('zh-CN')
    const userName = task.first_name && task.last_name ? 
      `${task.first_name} ${task.last_name}` : 
      task.username || '未知用户'

    return `
      <div class="task-item ${task.completed ? 'completed' : ''} ${task.priority}-priority">
        <div class="task-header">
          <div class="task-title">${task.title}</div>
          <div class="task-priority ${task.priority}">${getPriorityText(task.priority)}</div>
        </div>
        ${task.description ? `<div class="task-description">${task.description}</div>` : ''}
        <div class="task-meta">
          <div>
            <strong>分配给:</strong> ${userName}<br>
            <strong>创建时间:</strong> ${createdDate}<br>
            <strong>截止日期:</strong> ${dueDate}
          </div>
          <div class="task-actions">
            <button class="btn btn-sm ${task.completed ? 'btn-secondary' : 'btn-success'}" 
                    onclick="toggleTaskStatus(${task.id}, ${!task.completed})">
              ${task.completed ? '标记未完成' : '标记完成'}
            </button>
            <button class="btn btn-sm btn-danger" onclick="deleteTask(${task.id})">
              删除
            </button>
          </div>
        </div>
      </div>
    `
  }).join('')
}

// 更新用户选择器
function updateUserSelects() {
  const userOptions = users.map(user => 
    `<option value="${user.id}">${user.first_name || ''} ${user.last_name || ''} (@${user.username})</option>`
  ).join('')

  // 更新过滤器
  userFilter.innerHTML = `
    <option value="">所有用户</option>
    ${userOptions}
  `

  // 更新任务用户选择器
  taskUser.innerHTML = `
    <option value="">选择用户</option>
    ${userOptions}
  `
}

// 获取优先级文本
function getPriorityText(priority) {
  const priorityMap = {
    'low': '低',
    'medium': '中',
    'high': '高'
  }
  return priorityMap[priority] || priority
}

// 显示用户模态框
function showUserModal() {
  userForm.reset()
  userModal.style.display = 'flex'
}

// 隐藏用户模态框
function hideUserModal() {
  userModal.style.display = 'none'
}

// 显示任务模态框
function showTaskModal() {
  if (users.length === 0) {
    showError('请先添加用户后再创建任务')
    return
  }
  taskForm.reset()
  taskModal.style.display = 'flex'
}

// 隐藏任务模态框
function hideTaskModal() {
  taskModal.style.display = 'none'
}

// 处理用户表单提交
async function handleUserSubmit(e) {
  e.preventDefault()
  
  const formData = new FormData(userForm)
  const userData = {
    username: formData.get('username'),
    email: formData.get('email'),
    first_name: formData.get('firstName'),
    last_name: formData.get('lastName'),
    password_hash: '$2b$10$example.hash.for.demo' // 示例密码哈希
  }

  try {
    const result = await window.api.createUser(userData)
    if (result.success) {
      await loadUsers()
      hideUserModal()
      showSuccess('用户创建成功')
    } else {
      throw new Error(result.error)
    }
  } catch (error) {
    console.error('创建用户失败:', error)
    showError('创建用户失败: ' + error.message)
  }
}

// 处理任务表单提交
async function handleTaskSubmit(e) {
  e.preventDefault()
  
  const formData = new FormData(taskForm)
  const taskData = {
    title: formData.get('title'),
    description: formData.get('description'),
    user_id: parseInt(formData.get('user_id')),
    priority: formData.get('priority'),
    due_date: formData.get('due_date') || null
  }

  try {
    const result = await window.api.createTask(taskData)
    if (result.success) {
      await loadTasks()
      hideTaskModal()
      showSuccess('任务创建成功')
    } else {
      throw new Error(result.error)
    }
  } catch (error) {
    console.error('创建任务失败:', error)
    showError('创建任务失败: ' + error.message)
  }
}

// 处理用户过滤器变化
async function handleUserFilterChange(e) {
  const userId = e.target.value ? parseInt(e.target.value) : null
  await loadTasks(userId)
}

// 切换任务状态
async function toggleTaskStatus(taskId, completed) {
  try {
    const result = await window.api.updateTask(taskId, { completed })
    if (result.success) {
      await loadTasks()
      showSuccess(completed ? '任务已标记为完成' : '任务已标记为未完成')
    } else {
      throw new Error(result.error)
    }
  } catch (error) {
    console.error('更新任务状态失败:', error)
    showError('更新任务状态失败: ' + error.message)
  }
}

// 删除任务
async function deleteTask(taskId) {
  if (!confirm('确定要删除这个任务吗？')) {
    return
  }

  try {
    const result = await window.api.deleteTask(taskId)
    if (result.success) {
      await loadTasks()
      showSuccess('任务删除成功')
    } else {
      throw new Error(result.error)
    }
  } catch (error) {
    console.error('删除任务失败:', error)
    showError('删除任务失败: ' + error.message)
  }
}

// 显示成功消息
function showSuccess(message) {
  // 简单的提示实现，可以替换为更复杂的通知组件
  alert('✅ ' + message)
}

// 显示错误消息
function showError(message) {
  // 简单的提示实现，可以替换为更复杂的通知组件
  alert('❌ ' + message)
}

// =============================================================================
// 更新相关功能
// =============================================================================

// 设置更新UI
function setupUpdateUI() {
  // 监听更新状态变化
  if (window.updateManager) {
    window.updateManager.setStatusCallback((status, data) => {
      updateUpdateStatus(status, data)
    })
  }
}

// 处理检查更新按钮点击
async function handleCheckUpdate() {
  if (!window.updateManager) {
    showError('更新管理器未初始化')
    return
  }

  checkUpdateBtn.disabled = true
  checkUpdateBtn.innerHTML = '<span>🔄</span><span>检查中...</span>'
  
  try {
    await window.updateManager.checkForUpdates()
  } catch (error) {
    console.error('检查更新失败:', error)
    showError('检查更新失败: ' + error.message)
  } finally {
    setTimeout(() => {
      checkUpdateBtn.disabled = false
      checkUpdateBtn.innerHTML = '<span>🔄</span><span>检查更新</span>'
    }, 2000)
  }
}

// 更新更新状态显示
function updateUpdateStatus(status, data) {
  const statusMap = {
    'idle': { text: '就绪', class: 'idle' },
    'checking': { text: '检查中...', class: 'checking' },
    'available': { text: '发现新版本', class: 'available' },
    'not-available': { text: '已是最新', class: 'success' },
    'downloading': { text: '下载中...', class: 'downloading' },
    'downloaded': { text: '下载完成', class: 'downloaded' },
    'error': { text: '更新错误', class: 'error' }
  }

  const statusInfo = statusMap[status] || statusMap['idle']
  
  updateStatusText.textContent = statusInfo.text
  updateStatus.className = `update-status ${statusInfo.class}`
  
  // 显示或隐藏状态
  if (status === 'idle' || status === 'not-available') {
    setTimeout(() => {
      updateStatus.style.display = 'none'
    }, 3000)
  } else {
    updateStatus.style.display = 'flex'
  }
  
  // 如果正在下载，显示进度
  if (status === 'downloading' && data && data.percent !== undefined) {
    updateStatusText.textContent = `下载中... ${Math.round(data.percent)}%`
  }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initApp)

// 将函数暴露给全局作用域以供 HTML 中的 onclick 使用
window.toggleTaskStatus = toggleTaskStatus
window.deleteTask = deleteTask